<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>调色盘</title>
  <style>
  .color-picker-box {
    width:237px;
    height:162px;
    left:50%;
    top: 50%;
    position: absolute;
    transform: translate(-50%, -50%);
    border: 1px solid;
  }
  .color-picker_maincolor {
    display: block;
    position: absolute;
    border: 1px solid;
    left:210px;
    top:10px;
  }
  .color-picker_itemcolor {
    overflow: hidden;
    width: 16px;
    height: 101px;
    cursor: crosshair;
  }
  .color-picker_shvcolor {
    position: absolute;
    left: 10px;
    top: 10px;
    width: 181px;
    height: 101px;
    border: 1px solid;
    cursor: crosshair;
  }
  .color-picker_shvcolor > canvas {
    width: 100%;
  }
  .color-picker_bottom {
    top:120px;
    left:10px;
    position:absolute;
    display: flex;
  }
  .color-picker_selectcolor {
    width:100px;
    height:30px;
    margin-left:15px;
    background-color: #fff;
    border: 1px solid;
  }
  .color-picker_enterbtn {
    width:60px;
    height:30px;
    margin-left:30px;
  }
  </style>
</head>
<body>
  <div class="color-picker-box">
    <div class="color-picker_colordiv">
      <div class="color-picker_maincolor">
        <div class="color-picker_itemcolor">
        </div>
      </div>
      <div class="color-picker_shvcolor">
        <canvas id="color-picker"></canvas>
      </div>
    </div>
    <div class="color-picker_bottom">
      <div class="color-picker_selectcolor" id="color-picker-show"></div>
      <input class="color-picker_enterbtn" type="button" value="确定" onclick="sure()">
    </div>
  </div>
  <script src="../colorFormatTransfer/index.js"></script>
  <script>
    let canvas, ctx, colorRgba
    const initImage = function() {
      canvas = document.querySelector('#color-picker')
      ctx = canvas.getContext('2d')
      const img = new Image;
      img.src = './img/hs.png'
      img.onload = function() {//必须onload之后再画
        canvas.height = canvas.width * img.height / img.width
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        canvas.onmousedown = e => {
          pick(e)
        }
      }
    }
    const pick = function(e) {
      // 获取鼠标坐标
      let x = e.offsetX;
      let y = e.offsetY;
      // 获取图片像素信息
      let pixel = ctx.getImageData(x, y, 1, 1);
      let data = pixel.data;
      console.log(data);
      // 获取rgba值
      let rgba = 'rgba(' + data[0] + ',' + data[1] +',' + data[2] + ',' + (data[3] / 255) + ')';
      const color = document.querySelector('#color-picker-show')
      // 设置小正方形的背景颜色
      color.style.background =rgba;
      // 把拼接的字符串设置为元素的文本内容
      colorRgba = `${rgba}; ${this.rgbaToHex(rgba)}`
    }
    const sure = function() {
      console.log(colorRgba);
    }
    initImage()
  </script>
</div>
</body>
</html>